'''
Created on Feb 5, 2010

@author: mkiyer
'''

import matplotlib.pyplot as plt
import numpy as np

if __name__ == '__main__':
    import sys
    import collections
    
    f = open(sys.argv[1])    
    cols = map(int, sys.argv[2:])
    header = f.readline().strip().split('\t')[2:]
    
    if cols[0] == -1:
        for i, header_field in enumerate(header):
            print i, header_field
        sys.exit(0)        
    col_header = [header[x] for x in cols]    
    for i, col in enumerate(cols):
        print i, col_header[i] 
    
    keys = collections.defaultdict(lambda: 0)
    col_counts = np.zeros(len(cols), dtype=int) 
    
    for line in f:
        fields = line.strip().split('\t')        
        pos = fields[0]
        gnames = fields[1]        
        col_fields = [int(fields[x+2]) for x in cols]        

        print pos, gnames, col_fields
        # combine columns of interest into a unique key
        key = 0
        for i in xrange(len(col_fields)):
            v = col_fields[i]
            key = key | (v << i)
            col_counts[i] += v            
        keys[key] += 1
    
    # tss peak counts
    for i in xrange(len(col_counts)):
        print i, col_header[i], col_counts[i]

    # venn information    
    for k,v in keys.iteritems():
        key_cols = []
        for i in xrange(len(col_fields)):
            if (k & (1 << i)) != 0:
                key_cols.append(col_header[i])
        print k, v, key_cols

    print dict(keys)
    #n, bins, patches = plt.hist(keys)
    #print n